#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>



bool MainWindow::detectDS9()
{
    // 检查标准路径
    if(QFile::exists(ds9Path)) {
        ui->labelDs9Path->setText(ds9Path);
        return true;
    }
    // 检查标准路径
    const QStringList ds9Paths = {
        "/usr/bin/ds9",                      // Linux标准路径
        "/usr/local/bin/ds9",                // 手动安装路径
        "C:/Program Files/SAOImageDS9/ds9.exe",  // Windows路径
        QDir::homePath() + "/Applications/SAOImageDS9.app/Contents/MacOS/ds9" // macOS
    };

    // 自动检测可用路径
    for (const auto &path : ds9Paths) {
        if (QFile::exists(path)) {
            ds9Path = path;
            qInfo() << "DS9 detected at:" << path;
            ui->labelDs9Path->setText(ds9Path);
            return true;
        }
    }

    // 尝试通过系统命令查找
    QProcess which;
#ifdef Q_OS_WIN
    which.start("where", {"ds9.exe"});
#else
    which.start("which", {"ds9"});
#endif
    which.waitForFinished(1000);

    if (which.exitCode() == 0) {
        ds9Path = which.readAllStandardOutput().trimmed();
        ui->labelDs9Path->setText(ds9Path);
        return true;
    }

    return false;
}

void MainWindow::launchDS9(const QString& fitsPath)
{
    // 结束已有DS9进程
    if(!ds9Process.isNull()) {
        ds9Process->kill();
    }

    ds9Process.reset(new QProcess(this));

    // 设置DS9启动参数
    QStringList args;
    args << "-fits" << fitsPath
         << "-cmap" << "heat"
         << "-scale" << "log"
         << "-zoom" << "to fit";

    // 进程结束处理
    connect(ds9Process.data(), QOverload<int>::of(&QProcess::finished),
            [this](int exitCode) {
                qDebug() << "DS9 exited with code:" << exitCode;
            });

    // 启动DS9
    ds9Process->start(ds9Path, args);

    // 错误处理
    if(!ds9Process->waitForStarted(1000)) {
        QMessageBox::warning(this,
                             "DS9 Launch Failed",
                             "Could not start DS9. Please ensure it's installed at " + ds9Path);
    }
}
